//
//  PwdView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/16.
//

import AlertToast
import Combine
import SwiftUI
import TLCLock

class PwdModel: SheetModel {
    let device: LockDevice

    init(device: LockDevice) {
        self.device = device
    }

    deinit {
        debugPrint("pwd model deinit")
    }
}

struct PwdView: View {
    let model: PwdModel
    

    @State var id: String = ""
    @State var password: String = "123456"
    @State var forver: Bool = true
    @State var begin: Date = .init()
    @State var end: Date = Date().nextYear

    var body: some View {
        VStack {
            Text(model.device.macAddress)
                .bold()
                .foregroundColor(.orange)
                .font(.headline)
                .padding(.horizontal, 20)
                .frame(maxWidth: .infinity, alignment: .center)
            
            YxrInputView("密码ID", text: $id)
            YxrInputView("密码", text: $password)
            
            YxrToggleView(title: "永久", isOn: $forver)
            if !forver {
                YxrDatePicker(title: "开始时间", date: $begin)
                YxrDatePicker(title: "结束时间", date: $end)
            }
            
            YxrActionView(
                data: [
                    (0, "添加密码"),
                    (1, "删除"),
                    (2, "修改"),
                    (3, "冻结密码"),
                    (4, "解冻密码"),
                    (5, "清空密码"),
                ],
                itemBuilder: { value in
                    YXRActionItem(text: value.1) {
                        switch value.0 {
                        case 0: startAddPwd()
                        case 1: deletePwd()
                        case 2: modifyPwd()
                        case 3: updatePwd(status: .frozen)
                        case 4: updatePwd(status: .effective)
                        case 5: clearPwd()
                        default:
                            showToast("未实现的方法")
                        }
                    }
                }
            ).padding(.all, 10)
            
            LogView()
        }
        .yxrNavigationTitle("Password")
    }

    func startAddPwd() {
        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }
        
        let from: Date? = forver ? nil : begin
        let to: Date? = forver ? nil : end

        lockTask(desc: "add pwd") {
            let result = await model.device.addPassword(password: password, begin: from, end: to, lockKey: lockKey, trackId: Server.testTrackId)
            if result.isSuccess {
                if let idx = result.value {
                    self.id = "\(idx)"
                    Log.info("密码索引：\(idx)")
                }
            }
            return result
        }
    }

    func deletePwd() {
        guard let idx = UInt32(id) else {
            showToast("id 错误")
            return
        }
        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }
        lockTask(desc: "delete pwd") {
            await model.device.deletePassword(pwdId: idx, lockKey: lockKey, trackId: Server.testTrackId)
        }
    }

    func updatePwd(status: PasswordState) {
        guard let idx = UInt32(id) else {
            showToast("id 错误")
            return
        }

        let desc = status == .frozen ? "冻结" : "解冻"

        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        lockTask(desc: "\(desc) pwd") {
            await model.device.changePasswordState(pwdId: idx, state: status, lockKey: lockKey, trackId: Server.testTrackId)
        }
    }

    func modifyPwd() {
        guard let idx = UInt32(id) else {
            showToast("id 错误")
            return
        }

        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }
        
        let from: Date? = forver ? nil : begin
        let to: Date? = forver ? nil : end

        lockTask(desc: "modify") {
            await model.device.modifyPassword(pwdId: idx, newPassword: password, begin: from, end: to, lockKey: lockKey, trackId: Server.testTrackId)
        }
    }

    func clearPwd() {
        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        lockTask(desc: "clear pwd") {
            await model.device.clearAllPassword(lockKey: lockKey, trackId: Server.testTrackId)
        }
    }
}
